<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="adddialogVisible = true"
        >添加角色</el-button
      >
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- i1 === 0 ? 'bdtop' : ''通过三元表达式的形式判断添加bdtop -->
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vercent']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 每一行的分数都是24份，一级权限可占5份，其余交给二级三级权限 -->
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  :closable="true"
                  @close="RemoveRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  :class="[i2 !== 0 ? 'bdtop' : '', 'vercent']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      :closable="true"
                      type="success"
                      @close="RemoveRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      :closable="true"
                      @close="RemoveRightById(scope.row, item3.id)"
                      type="warning"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column property="roleName" label="角色名称">
        </el-table-column>
        <el-table-column property="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="RemoveUserById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-share"
                @click="ShowSetRightdialogVisible(scope.row)"
                >分配权限</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRightdialogVisible"
      width="50%"
      @close="setRightdialogVisibleClosed"
    >
      <!-- el-tree 树状显示列表数据，props树形控件配置属性，通过这个属性确定树形控件显示什么内容，如何确定父子关系 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        :show-checkbox="true"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addCloseDialog"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色管理" prop="roleName" width="50">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" width="50">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="EditdialogVisible"
      width="50%"
      @close="editCloseDialog"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      editForm: {},
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色管理名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色管理名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      rolesList: [],
      rightsList: [],
      roleId: '',
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      defKeys: [],
      adddialogVisible: false,
      EditdialogVisible: false,
      setRightdialogVisible: false,
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //   获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表错误')
      }
      //   成功操作
      this.rolesList = res.data
      console.log(this.rolesList)
    }, // 关闭对话框，清空文本
    addCloseDialog() {
      // 清空文本
      this.$refs.addFormRef.resetFields()
    }, // 添加用户
    addUser() {
      // 表单预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.adddialogVisible = false
        this.getRolesList()
      })
    }, // 关闭对话框，清空文本
    editCloseDialog() {
      this.$refs.editFormRef.resetFields()
    }, // 显示列表数据
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取错误')
      }
      this.editForm = res.data
      this.EditdialogVisible = true
    }, // 修改数据
    EditUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        // console.log(this.editForm.roleId)
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        this.EditdialogVisible = false
        this.getRolesList()
        this.$message.success('数据修改成功')
      })
    }, // 删除数据
    async RemoveUserById(id) {
      const removeResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // 捕捉错误
      // console.log(removeResult) // confirm | cancel
      if (removeResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    }, // 删除权限
    async RemoveRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 直接更新存在一个刷新页面闭合页面的bug
      // this.getRolesList()
      role.children = res.data
    }, // 获取树状列表权限
    async ShowSetRightdialogVisible(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data

      // 调用递归函数获取数据
      this.getdafKeys(role, this.defKeys)
      console.log(this.defKeys)
      this.setRightdialogVisible = true
    }, // 通过递归函数的形式获取三级节点 node节点数据，arr存放数据的数组
    getdafKeys(node, arr) {
      // 判断节点数据是否为三级节点 node
      if (!node.children) {
        return arr.push(node.id)
      }
      // 不是三级节点的处理函数
      node.children.forEach((item) => {
        this.getdafKeys(item, arr)
      })
    }, // 关闭对话框，清空defKeys的数据，防止数据累加
    setRightdialogVisibleClosed() {
      this.defKeys = []
    }, // 为角色添加权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idstr = keys.join(',')
      console.log(idstr)

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idstr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('数据更新失败')
      }
      this.$message.success('数据更新成功')
      this.getRolesList()
      this.setRightdialogVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vercent {
  display: flex;
  justify-content: center;
}
</style>
